<template>
  <el-container>
    <el-dialog
      v-model="dialogVisible"
      title="新增操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="form"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="ruleFormRef"
      >
        <el-form-item label="工作人员名:" prop="sid">
          <el-select
            v-model="form.sid"
            placeholder="选择工作人员名"
            style="width: 100%"
          >
            <el-option
              v-for="item in stafflist"
              :key="item.sid"
              :label="item.sname"
              :value="item.sid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商名字:" prop="pid">
          <el-select
            v-model="form.pid"
            placeholder="选择供应商名"
            style="width: 100%"
          >
            <el-option
              v-for="item in providerlist"
              :key="item.pid"
              :label="item.name"
              :value="item.pid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库名字:" prop="shid">
          <el-select
            v-model="form.shid"
            placeholder="选择仓库名"
            style="width: 100%"
          >
            <el-option
              v-for="item in storehouselist"
              :key="item.shid"
              :label="item.shname"
              :value="item.shid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="矿泉水名称:" prop="wid">
          <el-select
            v-model="form.wid"
            placeholder="选择矿泉水名"
            style="width: 100%"
          >
            <el-option
              v-for="item in waterlist"
              :key="item.wid"
              :label="item.wname"
              :value="item.wid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="送达时间:" prop="time">
          <el-date-picker
            v-model="form.time"
            type="datetime"
            placeholder="请挑选时间和日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="矿泉水数量:" prop="number">
          <el-input v-model.number="form.number" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="空桶数量:" prop="bottle">
          <el-input v-model.number="form.bottle" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmadd(form)">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="editVisible"
      title="编辑操作"
      width="30%"
      center
      draggable
    >
      <el-form
        :model="editform"
        class="addform"
        label-width="auto"
        :rules="addrules"
        ref="editFormRef"
      >
        <el-form-item label="工作人员名:" prop="sid">
          <el-select
            v-model="editform.sid"
            placeholder="选择工作人员名"
            style="width: 100%"
          >
            <el-option
              v-for="item in stafflist"
              :key="item.sid"
              :label="item.sname"
              :value="item.sid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="供应商名字:" prop="pid">
          <el-select
            v-model="editform.pid"
            placeholder="选择供应商名"
            style="width: 100%"
          >
            <el-option
              v-for="item in providerlist"
              :key="item.pid"
              :label="item.name"
              :value="item.pid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库名字:" prop="shid">
          <el-select
            v-model="editform.shid"
            placeholder="选择仓库名"
            style="width: 100%"
          >
            <el-option
              v-for="item in storehouselist"
              :key="item.shid"
              :label="item.shname"
              :value="item.shid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="矿泉水名称:" prop="wid">
          <el-select
            v-model="editform.wid"
            placeholder="选择矿泉水名"
            style="width: 100%"
          >
            <el-option
              v-for="item in waterlist"
              :key="item.wid"
              :label="item.wname"
              :value="item.wid"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="送达时间:" prop="time">
          <el-date-picker
            v-model="editform.time"
            type="datetime"
            placeholder="请挑选时间和日期"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="矿泉水数量:" prop="number">
          <el-input
            v-model.number="editform.number"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="空桶数量:" prop="bottle">
          <el-input
            v-model.number="editform.bottle"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmedit(editform)"
            >确认</el-button
          >
        </span>
      </template>
    </el-dialog>

    <el-header class="head">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="input1" placeholder="请输入订单号或者相关全名">
            <template #prefix>
              <el-icon class="el-input__icon"><search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="2">
          <el-button type="primary" @click="select(input1)">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="dialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-popconfirm
            confirm-button-text="Yes"
            cancel-button-text="No"
            :icon="InfoFilled"
            icon-color="red"
            title="你真的要确认批量删除消息么"
            @confirm="alldelete(multipleSelection)"
          >
            <template #reference>
              <el-button type="danger">批量删除</el-button>
            </template>
          </el-popconfirm>
        </el-col>
        <el-col :span="8"></el-col>
        <el-col :span="3"><span>仓库详情表</span></el-col>
      </el-row>
    </el-header>

    <el-main class="table-box">
      <el-table
        :data="tableData"
        border
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        @selection-change="changemult"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="phid"
          width="120"
          :index="indexMethod"
          label="订单号"
        />
        <el-table-column prop="sname" label="工作人员名" width="100">
        </el-table-column>
        <el-table-column prop="name" label="供应商名" width="80">
        </el-table-column>
        <el-table-column prop="shname" label="仓库名" width="110">
        </el-table-column>
        <el-table-column prop="wname" label="矿泉水名称" width="80">
        </el-table-column>
        <el-table-column prop="number" label="矿泉水数量" width="80">
        </el-table-column>
        <el-table-column prop="bottle" label="回收空桶数量" width="80">
        </el-table-column>
        <el-table-column prop="purchase" label="收购单价" width="80">
        </el-table-column>
        <el-table-column prop="total" label="总价" width="80">
        </el-table-column>
        <el-table-column prop="time" label="时间" width="160">
        </el-table-column>

        <el-table-column label="单项操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >

            <el-popconfirm
              confirm-button-text="Yes"
              cancel-button-text="No"
              :icon="InfoFilled"
              icon-color="red"
              title="你确定要删除该行消息么"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <div class="pagin">
      <el-pagination
        layout="prev, pager, next"
        :total="totalNumber"
        :page-size="Pagesize"
        :pager-count="10"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </el-container>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import {
  getstaff,
  getwater,
  getprovider,
  getstorehouse,
  getpurchase,
  getpurchasedata,
  updatepurchasebyid,
  savepurchase,
  deletepurchasebyid,
} from "@/apis/orderData.js";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    Search,
  },

  setup() {
    let multipleSelection = ref("");
    const input1 = ref("");
    const dialogVisible = ref(false);

    let totalNumber = ref(0);
    let currentPage = ref(1);
    let Pagesize = ref(5);

    let editVisible = ref(false);

    let listdata = ref("");
    let tableData = ref("");

    const stafflist = ref([]);
    const waterlist = ref([]);
    const providerlist = ref([]);
    const storehouselist = ref([]);

    const form = reactive({
      phid: "",
      sid: "",
      pid: "",
      wid: "",
      shid: "",
      number: "",
      time: "",
      total: "",
      bottle: "",
    });

    const editform = reactive({
      phid: "",
      sid: "",
      pid: "",
      wid: "",
      shid: "",
      number: "",
      time: "",
      total: "",
      bottle: "",
    });

    const addrules = reactive({
      sid: [
        {
          required: true,
          message: "请输入工作人员名字",
          trigger: "blur",
        },
      ],
      shid: [
        {
          required: true,
          message: "请输入仓库名",
          trigger: "blur",
        },
      ],
      wid: [
        {
          required: true,
          message: "请输入矿泉水名称",
          trigger: "blur",
        },
      ],
      pid: [
        {
          required: true,
          message: "请输入供应商名称",
          trigger: "blur",
        },
      ],
      time: [
        {
          required: true,
          message: "请选择时间",
          trigger: "blur",
        },
      ],
      number: [
        {
          required: true,
          message: "请输入矿泉水数量",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
      bottle: [
        {
          required: true,
          message: "请输入空桶数量",
          trigger: "blur",
        },
        { type: "number", message: "类型必须为数字" },
      ],
    });

    onMounted(() => {
      startmounted();
    });

    async function startmounted() {
      await getstafflist();
      await getproviderlist();
      await getstorehouselist();
      await getwaterlist();
      getdata();
    }

    function getstafflist() {
      let nowtime = Date.now();
      let beforetime = localStorage.getItem("stafftime");
      if (beforetime) {
        let trust = compareStorage(nowtime, beforetime, "stafflist");
        if (trust != null) {
          stafflist.value = JSON.parse(trust);
          return;
        }
      }
      getstaff().then((res) => {
        stafflist.value = res.data.page.list;
        localStorage.setItem("stafftime", nowtime);
        localStorage.setItem("stafflist", JSON.stringify(res.data.page.list));
      });
    }

    function getproviderlist() {
      let nowtime = Date.now();
      let beforetime = localStorage.getItem("providertime");
      if (beforetime) {
        let trust = compareStorage(nowtime, beforetime, "providerlist");
        if (trust != null) {
          providerlist.value = JSON.parse(trust);
          return;
        }
      }
      getprovider().then((res) => {
        providerlist.value = res.data.page.list;
        localStorage.setItem("providertime", nowtime);
        localStorage.setItem("providerlist", JSON.stringify(res.data.page.list));
      });
    }

    function getstorehouselist() {
      let nowtime = Date.now();
      let beforetime = localStorage.getItem("storehousetime");
      if (beforetime) {
        let trust = compareStorage(nowtime, beforetime, "storehouselist");
        if (trust != null) {
          storehouselist.value = JSON.parse(trust);
          return;
        }
      }
      getstorehouse().then((res) => {
        storehouselist.value = res.data.page.list;
        localStorage.setItem("storehousetime", nowtime);
        localStorage.setItem("storehouselist", JSON.stringify(res.data.page.list));
      });
    }

    function getwaterlist() {
      let nowtime = Date.now();
      let beforetime = localStorage.getItem("watertime");
      if (beforetime) {
        let trust = compareStorage(nowtime, beforetime, "waterlist");
        if (trust != null) {
          waterlist.value = JSON.parse(trust);
          return;
        }
      }

      getwater().then((res) => {
        waterlist.value = res.data.page.list;
        localStorage.setItem("watertime", nowtime);
        localStorage.setItem("waterlist", JSON.stringify(res.data.page.list));
      });
    }

    function mergearray(arr1, arr2) {
      const arrs = arr1.map((item) => {
        const data = arr2.find((i) => item.wid == i.wid);
        return {
          ...item,
          ...data,
        };
      });
      return arrs;
    }

    function mergestaff(arr1, arr2) {
      const arrs = arr1.map((item) => {
        const data = arr2.find((i) => item.sid == i.sid);
        return {
          ...item,
          ...data,
        };
      });
      return arrs;
    }

    function mergeprovider(arr1, arr2) {
      const arrs = arr1.map((item) => {
        const data = arr2.find((i) => item.pid == i.pid);
        return {
          ...item,
          ...data,
        };
      });
      return arrs;
    }

    function mergestorehouse(arr1, arr2) {
      const arrs = arr1.map((item) => {
        const data = arr2.find((i) => item.shid == i.shid);
        return {
          ...item,
          ...data,
        };
      });
      return arrs;
    }

    function getdata() {
      let page = currentPage.value;
      let size = Pagesize.value;
      getpurchase().then((res) => {
        listdata.value = res.data.page.list;
        listdata.value = mergearray(listdata.value, waterlist.value);
        listdata.value = mergestaff(listdata.value, stafflist.value);
        listdata.value = mergeprovider(listdata.value, providerlist.value);
        listdata.value = mergestorehouse(listdata.value, storehouselist.value);
        window.console.log(listdata.value);
        totalNumber.value = res.data.page.list.length;
        tableData.value = listdata.value.slice(page * size - size, page * size);
      });
    }

    function select(prop) {
      let name = {
        key: prop,
        wid: selectwaterid(prop),
        sid: selectstaffid(prop),
        shid: selectstorehouseid(prop),
        pid: selectproviderid(prop),
      };
      window.console.log(name);
      getpurchasedata(name).then((res) => {
        window.console.log(res.data.page.list);
        listdata.value = res.data.page.list;
        listdata.value = mergearray(listdata.value, waterlist.value);
        listdata.value = mergestaff(listdata.value, stafflist.value);
        listdata.value = mergeprovider(listdata.value, providerlist.value);
        listdata.value = mergestorehouse(listdata.value, storehouselist.value);
        totalNumber.value = res.data.page.list.length;
        currentPage.value = 1;
        tableData.value = listdata.value.slice(0, Pagesize.value);
      });
    }

    function handleEdit(index, row) {
      editVisible.value = true;
      editform.phid = row.phid;
      editform.sid = row.sid;
      editform.shid = row.shid;
      editform.pid = row.pid;
      editform.sid = row.sid;
      editform.wid = row.wid;
      editform.time = new Date(row.time);
      editform.number = row.number;
      editform.bottle = row.bottle;
    }

    function getphid(time, uid, sid, wid, number) {
      let year = time.getFullYear();
      let month =
        time.getMonth() < 10
          ? "0" + (time.getMonth() + 1)
          : time.getMonth() + 1;
      let date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
      let phid = [year, month, date, uid, sid, wid, number].join("");
      return phid;
    }

    function selectprice(id) {
      let selectedItem = {};
      selectedItem = waterlist.value.find((item) => {
        return item.wid === id;
      });
      return selectedItem.purchase;
    }

    function selectwaterid(wname) {
      let selectedItem = {};
      selectedItem = waterlist.value.find((item) => {
        return item.wname === wname;
      });
      if (selectedItem) {
        return selectedItem.wid.toString();
      }
      return null;
    }

    function selectstorehouseid(shname) {
      let selectedItem = {};
      selectedItem = storehouselist.value.find((item) => {
        return item.shname === shname;
      });
      if (selectedItem) {
        return selectedItem.shid.toString();
      }
      return null;
    }

    function selectproviderid(name) {
      let selectedItem = {};
      selectedItem = providerlist.value.find((item) => {
        return item.name == name;
      });
      if (selectedItem) {
        return selectedItem.pid.toString();
      } else {
        return null;
      }
    }

    function selectstaffid(sname) {
      let selectedItem = {};
      selectedItem = stafflist.value.find((item) => {
        return item.sname === sname;
      });
      if (selectedItem) {
        return selectedItem.sid.toString();
      } else {
        return null;
      }
    }

    function confirmadd(form) {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          form.phid = getphid(
            form.time,
            form.sid,
            form.shid,
            form.pid,
            form.wid
          );
          form.total = selectprice(form.wid) * form.number;
          form.time = form.time.getTime();

          savepurchase(form)
            .then((res) => {
              window.console.log(res.data);
              if (res.data.code == 0) {
                ElMessage({
                  message: "新增成功",
                  type: "success",
                });

                getdata();
              }
            })
            .catch(function (err) {
              ElMessage({
                message: "表单已存在,错误原因:" + err,
                type: "error",
              });
            });
          dialogVisible.value = false;
        } else {
          ElMessage({
            message: "输入表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function confirmedit(form) {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          form.total = selectprice(form.wid) * form.number;

          form.time = form.time.getTime();
          window.console.log(form.time);

          updatepurchasebyid(form).then((res) => {
            if (res.data.code == 0) {
              ElMessage({
                message: "编辑成功",
                type: "success",
              });
              getdata();
            } else {
              ElMessage({
                message: "编辑失败",
                type: "error",
              });
            }
          });
          editVisible.value = false;
        } else {
          ElMessage({
            message: "编辑表单不符合规则",
            type: "error",
          });
        }
      });
    }

    function alldelete(data) {
      window.console.log(data);
      if (data.length == 0) {
        ElMessage({
          message: "你好像没有选中删除的数据项",
          type: "warning",
        });
      } else {
        deletepurchasebyid(data).then((res) => {
          if (res.data.code == 0) {
            ElMessage({
              message: "删除成功",
              type: "success",
            });
            getdata();
          } else {
            ElMessage({
              message: "删除失败",
              type: "error",
            });
          }
        });
      }
    }

    function handleDelete(index, row) {
      //删除操作
      let key = [row.phid];

      deletepurchasebyid(key).then((res) => {
        if (res.data.code == 0) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          getdata();
        } else {
          ElMessage({
            message: "删除失败",
            type: "error",
          });
        }
      });
    }

    function handleCurrentChange(page) {
      currentPage.value = page;
      let size = Pagesize.value;
      tableData.value = listdata.value.slice(page * size - size, page * size);
    }

    function indexMethod(index) {
      return index + 1 + (currentPage.value - 1) * Pagesize.value;
    }

    function changemult(val) {
      let ids = [];
      for (let i in val) {
        ids.push(val[i].phid);
      }
      multipleSelection.value = ids;
    }

    function compareStorage(newtime, oldtime, Storagename) {
      if (newtime - oldtime < 8640000) {
        let data = localStorage.getItem(Storagename);
        return data;
      } else {
        localStorage.removeItem(Storagename);
      }
      return null;
    }

    return {
      input1,
      tableData,
      multipleSelection,
      stafflist,
      providerlist,
      storehouselist,
      waterlist,
      dialogVisible,
      editVisible,
      select,
      addrules,
      confirmadd,
      indexMethod,
      editform,
      totalNumber,
      currentPage,
      Pagesize,
      handleEdit,
      handleDelete,
      confirmedit,
      alldelete,
      form,
      changemult,
      handleCurrentChange,
    };
  },
});
</script>
<style scoped>
.head {
  font-size: 18px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
.addform >>> .el-form-item {
  padding-left: 8%;
}
.addform >>> .el-input {
  width: 80%;
}
.pagin {
  text-align: center;
  margin-left: -10%;
}
</style>